<script lang="ts" setup>
	import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue"
	import { config } from "@/config/axios/config"
	import { NewsApi } from '@/api/news';
	import { message, type UploadProps } from 'ant-design-vue';
	import { usePopupStore } from '@/stores/popup'
	import { useUserStore } from '@/stores/user';
	import { PlusOutlined } from '@ant-design/icons-vue';
	import '@wangeditor/editor/dist/css/style.css' // 引入 css
	import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
	type InsertFnType = (url : string, alt : string, href : string) => void
	const editorRef = shallowRef()
	let news = ref({
		title: "",
		content: "",
		source: "",
		cover: "",
		type: 1,
	})
	let isFullScreen = ref<boolean>(false)
	const toolbarConfig = {}
	const editorConfig = {
		placeholder: '请输入内容...',
		MENU_CONF: {
			uploadImage: {
				fieldName: 'file',
				maxFileSize: 10 * 1024 * 1024,
				server: config.baseUrl + '/api/uploadFile',
				customInsert(res : any, insertFn : InsertFnType) {
					insertFn(res.data, "", "")
				},
			},
			uploadVideo: {
				fieldName: 'file',
				maxFileSize: 100 * 1024 * 1024,
				server: config.baseUrl + '/api/uploadFile',
				customInsert(res : any, insertFn : InsertFnType) {
					insertFn(res.data, "", "")
				},
			}
		}
	}
	// 组件销毁时，也及时销毁编辑器
	onBeforeUnmount(() => {
		const editor = editorRef.value
		if (editor == null) return
		editor.destroy()
	})
	const handleCreated = (editor : any) => {
		editor.on('fullScreen', () => { isFullScreen.value = true })
		editor.on('unFullScreen', () => { isFullScreen.value = false })
		editorRef.value = editor // 记录 editor 实例，重要！
	}
	let mode = ref<string>('default')

	const userStore = useUserStore()
	const usePopup = usePopupStore()
	let exit = (type : string) => {
		usePopup.setPopup(type)
		news.value = {
			title: "",
			content: "",
			source: "",
			cover: "",
			type: 1,
		}
	}
	const type = [
		{
			value: 0,
			label: '顶部',
		},
		{
			value: 1,
			label: "业内资讯",
		},
		{
			value: 2,
			label: "公司新闻",
		},
		{
			value: 3,
			label: "通知公告",
		}
	]
	const previewVisible = ref(false);
	const previewImage = ref('');
	const previewTitle = ref('');

	const fileList = ref<any>([]);

	const handleCancel = () => {
		previewVisible.value = false;
		previewTitle.value = '';
	};
	function getBase64(file : File) {
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = () => resolve(reader.result);
			reader.onerror = error => reject(error);
		});
	}
	const handlePreview = async (file : any) => {
		if (!file.url && !file.preview) {
			file.preview = (await getBase64(file.originFileObj)) as string;
		}
		previewImage.value = file.url || file.preview;
		previewVisible.value = true;
		previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
	};

	const submit = () => {
		for (let file of fileList.value) {
			news.value.cover = file.response.data.replace(config.baseUrl, "");
		}
		if (news.value.title.length == 0) {
			message.error('标题不能为空');
			return false
		}
		if (news.value.content.length == 0) {
			message.error('内容不能为空');
			return false
		}
		if (news.value.cover == "") {
			message.error('请添加课程封面');
			return false
		}
		NewsApi.addNews({
			...news.value
		}).then((res : any) => {
			if (res.code == 1) {
				message.success(res.message);
				exit('')
			} else if (res.code == 0) {
				message.error(res.message);
			}
		})
	}
</script>

<template>
	<a-modal :open="true" :footer="null" @cancel="exit('')" centered width="1000px" :closable="!isFullScreen">
		<div class="content">
			<div class="title">
				<div class="line"></div>发布新闻
			</div>
			<div class="info-box">
				<div class="item">
					<div class="lebel">
						<span>*</span>类型：
					</div>
					<div class="text">
						<a-select v-model:value="news.type" size="large" :options="type" placeholder="请选择类型"
							class="select"></a-select>
					</div>
				</div>
				<div class="item">
					<div class="lebel">
						<span>*</span>标题：
					</div>
					<div class="text">
						<input type="text" v-model="news.title" placeholder="请输入标题" class="input" />
					</div>
				</div>
				<div class="item">
					<div class="lebel">
						来源：
					</div>
					<div class="text">
						<input type="text" v-model="news.source" placeholder="请输入来源" class="input" />
					</div>
				</div>
				<div class="item img-item">
					<div class="lebel">
						<span>*</span>封面
					</div>
					<div class="text">
						<a-upload v-model:file-list="fileList" :action="config.baseUrl+'/api/uploadFile'"
							list-type="picture-card" @preview="handlePreview">
							<div
								v-if="fileList.length < 1">
								<plus-outlined />
								<div style="margin-top: 8px">上传图片</div>
							</div>
						</a-upload>
						<a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
							<img alt="example" style="width: 100%" :src="previewImage" />
						</a-modal>
					</div>
				</div>
				<div class="item signature">
					<div class="lebel"></div>
					<div class="text">
						<div style="border: 1px solid #ccc">
							<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
								:defaultConfig="toolbarConfig" :mode="mode" />
							<Editor style="height: 300px; overflow-y: hidden;" v-model="news.content"
								:defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
						</div>
					</div>
				</div>
			</div>
			<div class="btn-box" v-if="!isFullScreen">
				<a-button type="primary" class="btn" @click="submit">
					保存
				</a-button>
				<a-button type="default" class="btn" @click="exit('')">
					取消
				</a-button>
			</div>
		</div>
	</a-modal>
</template>

<style lang="scss" scoped>
	.ant-modal-content {
		padding: 0;
	}

	.content {
		padding: 0 20px;

		.title {
			font-size: 18px;
			padding-bottom: 15px;
			border-bottom: 1px solid #ccc;
			display: flex;
			align-items: center;
			font-weight: bold;
			.line {
				border-radius: 4px;
				width: 4px;
				height: 20px;
				background-color: #1677ff;
				margin-right: 8px;
			}
		}

		.info-box {
			margin-top: 20px;
			display: flex;
			flex-wrap: wrap;

			.item {
				margin-top: 20px;
				display: flex;
				align-items: center;

				.lebel {
					margin-right: 10px;
					width: 50px;
					text-align: right;

					span {
						color: red;
					}
				}

				.text {
					flex: 1;

					.textarea {
						margin-top: 10px;
					}

					.select {
						width: 200px;
						font-size: 14px;
						margin-right: 100px;
					}

					.select ::v-deep .ant-select-selector {
						font-size: 14px;
					}


					.input {
						width: 500px;
						height: 40px;
						border: solid 1px #d9d9d9;
						border-radius: 6px;
						font-size: 14px;
					}

					.input-width {
						width: 500px;
						margin-right: 40px;
					}

					.input:focus {
						box-shadow: 0 0 0 2px rgb(5, 145, 255, 10%);
						border-color: #4096ff;
					}

					.input:hover {
						border-color: #4096ff;
					}

					::placeholder {
						color: #bfbfbf;
						font-size: 14px;
					}
				}
			}

			.img-item {
				min-width: 600px;
			}

			.signature {
				margin-top: 30px;
				display: block;
				width: 100%;
			}
		}

		.btn-box {
			margin-top: 30px;
			display: flex;
			align-items: center;
			justify-content: center;

			.btn {
				margin: 0 20px;
			}
		}

	}
</style>